#include "databasemanager.h"
#include <QDebug>

bool DatabaseManager::openDB()
    {
    if (db.isOpen()) return true;
    db = QSqlDatabase::addDatabase("QSQLITE");
    QString path(QDir::home().path());
    path.append(QDir::separator()).append("my.db.sqlite");
    path = QDir::toNativeSeparators(path);
    db.setDatabaseName(path);
    return db.open();
    }

bool DatabaseManager::deleteDB()
    {
    db.close();
    QString path(QDir::home().path());
    path.append(QDir::separator()).append("my.db.sqlite");
    path = QDir::toNativeSeparators(path);
    return QFile::remove(path);
    }

bool DatabaseManager::createDownloadsTable()
    {
    bool ret = false;
    if (db.isOpen())
        {
        QSqlQuery query;
        ret = query.exec("create table if not exists download "
                  "(id integer primary key, "
                  "url varchar(70), "
                  "folder varchar(200), "
                  "progress integer, "
                  "priority integer)");

        }
    return ret;
    }

int DatabaseManager::insertDownload(QString url, QString folder, int progress = 0, int priority = 5)
    {
    int newId = -1;
    bool ret = false;

    if (db.isOpen())
        {

        QSqlQuery query;
        ret = query.exec(QString("insert into download values(NULL,'%1','%2',%3, %4)")
        .arg(url).arg(folder).arg(progress).arg(priority));

        if (ret)
            {
            newId = query.lastInsertId().toInt();
            }

        }
    return newId;
    }

int DatabaseManager::insertProgressDownload(int id, int progress)
    {
    if (db.isOpen())
        {
        QSqlQuery query;
        bool ret = query.exec(QString("update download set progress='%2' where id='%1'")
        .arg(id).arg(progress));
        }
    return id;
}

void DatabaseManager::deleteDownload(int id)
{
    if (db.isOpen())
        {
        QSqlQuery query;
        bool ret = query.exec(QString("delete from download where id='%1'").arg(id));
        }
}

void DatabaseManager::close()
{
    db.close();
}
